package com.zhao.utils

import java.sql.{Connection, DriverManager}
import java.util

/**
 * Description: mysql连接池<br/>
 * Copyright (c) ，2020 ， 赵 <br/>
 * This program is protected by copyright laws. <br/>
 * Date： 2020/8/25 11:20
 *
 * @author 柒柒
 * @version : 1.0
 */

object JdbcUtil {
  private val max_connection = 10 //连接池中连接存放数
  private val connection_num = 10 //产生连接数
  private var current_num = 0 //当前连接池已产生的连接数
  private val pools = new util.LinkedList[Connection] //连接池

  /**
   * 加载驱动
   */
  private def before(): Unit ={
    if (current_num >= max_connection && !pools.isEmpty()){
      print("busyness")
      Thread.sleep(2000)
      before() //递归调用自己
    }else{
      Class.forName(CommonUtil.load.getString("db.default.driver"))
    }
  }

  /**
   * 获得连接数
   */
  private def initConn()= {
    val connection: Connection = DriverManager.getConnection(
      CommonUtil.load.getString("db.default.url"),
      CommonUtil.load.getString("db.default.user"),
      CommonUtil.load.getString("db.default.password")
    )

    connection
  }

  /**
   * 初始化连接池
   */
  private def initConnectionPool() = AnyRef.synchronized({
      if(pools.isEmpty){
        before()
        for (i <- 1 to connection_num){
          pools.push(initConn())
          current_num += 1
        }
      }
    pools
  })

  /**
   * 获得连接
   */
  def getConn()={
    initConnectionPool()
    //计数器递减1
    current_num -= 1
    pools.poll() //与此同时,从连接池中删除一个连接的实例
  }

  /**
   * 释放连接
   */
  def releaseCon(con:Connection) ={
    pools.push(con)
  }
}
